<?php

namespace Morrow;

class PageController extends DefaultController {
	public function run() {

		$this->form->loadDef(
			array('myform' => array(

		            "title" => array(
		            	"type" => "text",
		            	"required" => true,
    
	            	),

	            	"content" => array(
		            	"type" => "textarea",

	            	),
            	)
            )
        );


		if(!$this->session->get("uid")){
			$this -> url -> redirect('home');
		}

        //set data

		$this->form->setInput($this->input->get());

		if($this -> form -> isSubmitted('myform')) {
    			$valid = $this -> form -> validate('myform');

            	$this->view->setContent($this->form->getErrors('myform'), "error");

    				if ($valid) {
        		        $formdata = $this -> form -> getValues('myform');
        				
                        $this->load('Db', $this->config->get('db'));

                        $slq=$this->db->Result('
                            SELECT wid
                            FROM webapps
                            WHERE uid = ?',
                            $this->session->get("uid"));

                        $wid_count=count($slq['RESULT']);

                        //var_dump($wid_count);

                        if($wid_count>2){

                            $this->form->setError('myform','title',$this->language->_('你的Webapp的数量已上限') );

                        }
                        else{
                            //var_dump('yes');
                            $now = date("Y-m-d H:i:s",time());
                            $add_time = array('add_time'=> $now);

                            $code= md5($now);
                            $add_code=array('code'=>$code);

                            $uid =array('uid' => $this->session->get("uid"));

                            $data_add_uid=array_merge($formdata, $uid);
                            $data_add_add_time=array_merge($data_add_uid, $add_time);
                            $data_add_add_code=array_merge($data_add_add_time, $add_code);

                            //$data['password'] = md5($data['password']);

                            $this->db->insertSafe('webapps', $data_add_add_code, true);

                            // set messenger
                            $this->session->set('messenger', 'add1');

                            //var_dump($data);
                            $this -> url -> redirect('user');
                        }
    				} 
    				else {
    				}
		}		

	}
}